from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from config import DevelopmentConfig


# 为了不独立于flask上下文
class DBUtil:
    @staticmethod
    def get_engine():
        DATABASE_URI = DevelopmentConfig.SQLALCHEMY_DATABASE_URI
        engine = create_engine(DATABASE_URI, echo=False, pool_size=DevelopmentConfig.SQLALCHEMY_POOL_SIZE,
                               max_overflow=DevelopmentConfig.SQLALCHEMY_MAX_OVERFLOW, pool_recycle=60*5)
        return engine

    @staticmethod
    def get_thread_session():
        thread_local = __import__('threading').local()
        if not hasattr(thread_local, 'db_session'):
            engine = DBUtil.get_engine()
            session_factory = sessionmaker(bind=engine)
            db_session = scoped_session(session_factory)
            thread_local.db_session = db_session
        return thread_local.db_session()
